#!/usr/bin/env bash

# Copyright 2021 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetesValidating:
- name: d8-authz-multitenancy.deckhouse.io
  includeSnapshotsFrom: ["d8-authz-webhook-cm"]
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["*"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["clusterauthorizationrules"]
    scope:       "Cluster"
kubernetes:
- name: d8-authz-webhook-cm
  apiVersion: v1
  kind: ConfigMap
  executeHookOnEvent: []
  executeHookOnSynchronization: false
  keepFullObjectsInMemory: false
  nameSelector:
    matchNames:
    - user-authz-webhook
  namespace:
    nameSelector:
      matchNames: ["d8-user-authz"]
EOF
}

# This hook checks MultiTenancy flag for user-authz module
# if flag is enabled - CM: user-authz-webhook is exists and we just exit
# if flag is disabled - we check CR ClusterAuthorizationRule for 'allowAccessToSystemNamespaces', 'limitNamespaces' and 'namespaceSelector'
# if any of those exists - disallow creation because of MultiTenancy

function __main__() {
  # don't check ClusterAuthorizationRule if MultiTenancy is enabled
  enableMultiTenancy=$(context::jq -r '.snapshots.["d8-authz-webhook-cm"] | length > 0')
  if [[ "$enableMultiTenancy" == "true" ]]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":true}
EOF
    return 0;
  fi

  allowAccessToSystemNamespaces=$(context::jq -rc '.review.request.object.spec.allowAccessToSystemNamespaces')
  if [[ "$allowAccessToSystemNamespaces" == "true" ]]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"You must turn on userAuthz.enableMultiTenancy to use allowAccessToSystemNamespaces flag in your ClusterAuthorizationRule resources (EE Only)."}
EOF
    return 0
  fi

  namespaceSelectorEnabled=$(context::jq -rc '.review.request.object.spec.namespaceSelector')
  if [[ "$namespaceSelectorEnabled" != "null" ]]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"You must turn on userAuthz.enableMultiTenancy to use namespaceSelector option in your ClusterAuthorizationRule resources (EE Only)."}
EOF
    return 0
  fi

  limitNamespacesEnabled=$(context::jq -rc '.review.request.object.spec.limitNamespaces // [] | length > 0')
  if [[ "$limitNamespacesEnabled" == "true" ]]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"You must turn on userAuthz.enableMultiTenancy to use limitNamespaces option in your ClusterAuthorizationRule resources (EE Only)."}
EOF
    return 0
  fi

  # allowed response
  cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":true}
EOF
}

hook::run "$@"
